<?php

namespace App\Admin\Auth;

use App\admin\BaseController;
use App\Http\Models\AdminNode;
use App\Http\Models\AdminRole;
use App\Http\Models\AdminRoleNode;
use App\Utils\Code;
use Illuminate\Http\Request;

/**
 * 角色控制器
 */
class RolesController extends BaseController
{
	
	/**
	 * 角色列表显示
	 */
	public function index()
	{
		$list = AdminRole::all()->toArray();
		$count = AdminRole::count();
		return view('admin/roles/index', ['list' => $list, 'count' => $count]);
	}

	/**
	 * 角色编辑显示
	 */
	public function edit($id = false)
	{
		$role = [];
		if ($id) $role = AdminRole::find($id) -> toArray();
		return view('admin/roles/edit', ['role' => $role]);
	}

	/**
	 * 保存角色
	 */
	public function save(Request $request)
	{
		$data = $request->input();
		if (!isset($data['name']) || !$data['name']) return renderError(Code::PARAM_IS_ERROR);
		$roleName = AdminRole::where(['name' => $data['name']]);

		if (isset($data['id']) && $data['id']) {
			$sysRole = AdminRole::find($data['id']);		
			$roleName->where('id', '<>', $data['id']);
		} else {
			$sysRole = new AdminRole();
		}
		if ($roleName->first()) return renderError(Code::SAVE_EXISTS_FAILED);

		$result = $sysRole->fill($data)->save();
		if ($result) {
			return renderSuccess('保存成功');
		} else {
			return renderError(Code::SAVE_FAILED);
		}
	}

	/**
	 * 删除角色
	 */
	public function delete($id)
	{
		if (!$id) return renderError(Code::PARAM_IS_ERROR);
		$node = AdminRole::find($id);
		if (!$node) {
			return renderError(Code::FAILED_TO_FIND_DATA);
		} 
		if ($node->delete()) {
			return renderSuccess('删除角色成功');
		} else {
			return renderError(Code::DELETE_FAILED);
		}
	}

	/**
	 * 节点授权显示
	 */
	public function editAuth($id)
	{
		$nodeList = AdminNode::get(['id', 'name as title', 'pid'])->toArray();
		$checkedList = AdminRoleNode::where(['role_id' => $id])->with(['nodes'])->get()->toArray();
		$checked = $this->createChildrenData($checkedList);
		return view('admin/roles/auth', ['roleId' => $id, 'nodeList' => getTree($nodeList), 'checked' => $checked]);
	}

	/**
	 * 节点授权保存
	 */
	public function authSave(Request $request)

	{	
		$data = $request->input();
		if (!isset($data['role_id']) || !($roleId = $data['role_id'])) return renderError(Code::PARAM_IS_ERROR);
		$selectedList = [];
		if (isset($data['checked'])) $selectedList = $this->createSelectedList($data['checked'], $roleId);
		AdminRoleNode::where(['role_id' => $roleId])->delete();
		$result = AdminRoleNode::insert($selectedList);
		if ($result) return renderSuccess('保存成功');
		return renderError(Code::SAVE_FAILED);
	}

	/**
	 * 递归生成选中数组
	 * @param array $data 源数据
	 * @return array $list 
	 */
	protected function createSelectedList($data, $roleId)
	{
		$createdAt = date('Y-m-d H:i:s');
		$list = [];
		foreach ($data as $value) {
			if (isset($value['id']) && $value['id']) $list[] = ['node_id' => $value['id'], 'role_id' => $roleId, 'created_at' => $createdAt];
			if (isset($value['children']) && $value['children']) $list = array_merge($list, $this->createSelectedList($value['children'], $roleId));
		}
		return $list;
	}

	/**
	 * 筛选出没有子集的所有id集合
	 * @param array $data
	 * @return array
	 */		
	protected function createChildrenData($data)
	{
		foreach ($data as $key => $value) {
			foreach ($data as $k => $val) {
				if ($value['nodes']['id'] == $val['nodes']['pid']) {
					unset($data[$key]);
					break;
				}
			}
		}
		return array_column($data, 'node_id');
	}

}